package ace.oauth2.provider.common.support;

import org.redisson.api.RedissonClient;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;

import java.util.concurrent.TimeUnit;

/**
 * @author Caspar
 * @contract 279397942@qq.com
 * @create 2020/10/21
 * @description redis授权码模式授权码服务-操作授权码生成、存储、删除
 **/
public class RedissonAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {


    private static final String AUTHORIZATION_CODE = "authorization:code:";
    private RedissonClient redissonClient;
    /**
     * 授权码有效时长
     */
    private Long expireInSeconds = TimeUnit.MINUTES.toSeconds(5);

    /**
     * key 前缀
     */
    private String prefix = "";

    public RedissonAuthorizationCodeServices(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }


    public void setExpireInSeconds(Long expireInSeconds) {
        this.expireInSeconds = expireInSeconds;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    /**
     * 将随机生成的授权码存到redis中
     *
     * @param code
     * @param authentication
     * @return void
     */
    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        String key = buildKey(AUTHORIZATION_CODE + code);
        redissonClient.getBucket(key).set(authentication, expireInSeconds, TimeUnit.SECONDS);
    }

    /**
     * 取出授权码并删除授权码(权限码只能用一次，调试时可不删除，code就可多次使用)
     *
     * @param code
     * @return org.springframework.security.oauth2.provider.OAuth2Authentication
     */
    @Override
    protected OAuth2Authentication remove(String code) {
        String key = buildKey(AUTHORIZATION_CODE + code);
        return redissonClient.<OAuth2Authentication>getBucket(key).getAndDelete();
    }

    private String buildKey(String key) {
        return prefix + key;
    }
}
